<template>
  <div class="image-path-test">
    <h2>图片路径测试</h2>
    
    <!-- 输入测试路径 -->
    <div class="test-section">
      <h3>测试图片路径</h3>
      <el-input
        v-model="testPath"
        placeholder="输入图片路径，如: uploads/01a1910"
        style="width: 400px; margin-bottom: 10px;"
      />
      <el-button @click="testImagePath" type="primary">测试路径</el-button>
    </div>

    <!-- 显示构建的URL列表 -->
    <div class="url-list" v-if="possibleUrls.length > 0">
      <h3>构建的URL列表:</h3>
      <div v-for="(url, index) in possibleUrls" :key="index" class="url-item">
        <div class="url-info">
          <span class="url-index">{{ index + 1 }}.</span>
          <span class="url-text">{{ url }}</span>
          <span class="url-status" :class="urlStatuses[index]">
            {{ urlStatuses[index] === 'loading' ? '加载中...' : 
               urlStatuses[index] === 'success' ? '成功' : 
               urlStatuses[index] === 'error' ? '失败' : '未测试' }}
          </span>
        </div>
        <img 
          v-if="urlStatuses[index] === 'success'"
          :src="url" 
          class="test-image"
          alt="测试图片"
        />
      </div>
    </div>

    <!-- 从数据库加载实际数据 -->
    <div class="data-section">
      <h3>从数据库加载实际数据</h3>
      <el-button @click="loadActualData" type="success">加载出库单数据</el-button>
      
      <div v-if="actualData.length > 0" class="actual-data">
        <h4>数据库中的图片路径:</h4>
        <div v-for="item in actualData" :key="item.outboundId" class="data-item">
          <div class="item-info">
            <strong>出库单号:</strong> {{ item.outboundOrderNumber }}
            <br>
            <strong>缩略图路径:</strong> {{ item.bkThumbnail || '无' }}
          </div>
          <div v-if="item.bkThumbnail" class="image-test">
            <img 
              :src="getImageUrl(item.bkThumbnail)" 
              class="actual-image"
              @load="handleImageLoad(item.outboundId)"
              @error="handleImageError(item.outboundId)"
              alt="实际图片"
            />
            <div class="image-status" :class="imageStatuses[item.outboundId]">
              {{ imageStatuses[item.outboundId] === 'loading' ? '加载中...' : 
                 imageStatuses[item.outboundId] === 'success' ? '成功' : 
                 imageStatuses[item.outboundId] === 'error' ? '失败' : '未测试' }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllOutboundOrders } from '@/api/outboundOrder'

// 配置后端服务器地址（用于图片访问）
const BACKEND_SERVER_URL = 'http://localhost:5265'

const testPath = ref('uploads/01a1910')
const possibleUrls = ref<string[]>([])
const urlStatuses = ref<string[]>([])
const actualData = ref<any[]>([])
const imageStatuses = reactive<{[key: number]: string}>({})

// 获取图片URL，修复图片显示问题
const getImageUrl = (url: string): string => {
  if (!url) {
    console.log('getImageUrl: 空URL')
    return ''
  }

  console.log('getImageUrl 输入:', url)

  // 如果是blob URL，检查是否有效
  if (url.startsWith('blob:')) {
    const blobMatch = url.match(/blob:https?:\/\/[^\/]+\/([a-f0-9-]+)/)
    if (!blobMatch) {
      console.warn('无效的blob URL格式:', url)
      return ''
    }
    console.log('getImageUrl: 返回blob URL:', url)
    return url
  }

  // 如果是data URL，直接返回
  if (url.startsWith('data:')) {
    console.log('getImageUrl: 返回data URL:', url)
    return url
  }

  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    console.log('getImageUrl: 返回完整URL:', url)
    return url
  }

  // 如果是后端返回的文件路径，尝试多种可能的路径格式
  if (url.includes('uploads/') || url.includes('outbound/') || url.includes('.png') || url.includes('.jpg') || url.includes('.jpeg')) {
    // 尝试多种可能的路径格式
    const possiblePaths = [
      // 直接使用后端服务器地址（因为图片在后端服务器上）
      `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}`,
      `${BACKEND_SERVER_URL}/${url}`,
      // 前端服务器路径（作为备选）
      `${window.location.origin}/uploads/${url.replace(/^uploads\//, '')}`,
      `${window.location.origin}/api/uploads/${url}`,
      `${window.location.origin}/static/uploads/${url}`,
      `${window.location.origin}/public/uploads/${url}`,
      `${window.location.origin}/${url}`,
      // 添加更多可能的路径
      `${window.location.origin}/images/${url}`,
      `${window.location.origin}/assets/${url}`,
      `${window.location.origin}/files/${url}`,
      `${window.location.origin}/media/${url}`,
      `${window.location.origin}/upload/${url}`,
      `${window.location.origin}/uploaded/${url}`,
      `${window.location.origin}/uploads/outbound/${url.replace(/^uploads\//, '')}`,
      `${window.location.origin}/api/upload/${url}`,
      `${window.location.origin}/api/file/${url}`,
      `${window.location.origin}/api/media/${url}`
    ]

    console.log('getImageUrl: 原始路径:', url)
    console.log('getImageUrl: BACKEND_SERVER_URL:', BACKEND_SERVER_URL)
    console.log('getImageUrl: window.location.origin:', window.location.origin)
    console.log('getImageUrl: 可能的路径:', possiblePaths)

    return possiblePaths[0]
  }

  // 其他情况，尝试作为相对路径处理
  console.log('getImageUrl: 返回相对路径:', url)
  return url
}

// 测试图片路径
const testImagePath = () => {
  if (!testPath.value) {
    ElMessage.warning('请输入测试路径')
    return
  }

  // 构建可能的URL列表
  const url = testPath.value
  possibleUrls.value = [
    // 直接使用后端服务器地址（因为图片在后端服务器上）
    `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}`,
    `${BACKEND_SERVER_URL}/${url}`,
    // 前端服务器路径（作为备选）
    `${window.location.origin}/uploads/${url.replace(/^uploads\//, '')}`,
    `${window.location.origin}/api/uploads/${url}`,
    `${window.location.origin}/static/uploads/${url}`,
    `${window.location.origin}/public/uploads/${url}`,
    `${window.location.origin}/${url}`,
    // 添加更多可能的路径
    `${window.location.origin}/images/${url}`,
    `${window.location.origin}/assets/${url}`,
    `${window.location.origin}/files/${url}`,
    `${window.location.origin}/media/${url}`,
    `${window.location.origin}/upload/${url}`,
    `${window.location.origin}/uploaded/${url}`,
    `${window.location.origin}/uploads/outbound/${url.replace(/^uploads\//, '')}`,
    `${window.location.origin}/api/upload/${url}`,
    `${window.location.origin}/api/file/${url}`,
    `${window.location.origin}/api/media/${url}`
  ]

  // 初始化状态
  urlStatuses.value = new Array(possibleUrls.value.length).fill('loading')

  // 测试每个URL
  possibleUrls.value.forEach((url, index) => {
    const img = new Image()
    img.onload = () => {
      urlStatuses.value[index] = 'success'
      console.log(`URL ${index + 1} 加载成功:`, url)
    }
    img.onerror = () => {
      urlStatuses.value[index] = 'error'
      console.log(`URL ${index + 1} 加载失败:`, url)
    }
    img.src = url
  })
}

// 加载实际数据
const loadActualData = async () => {
  try {
    const response = await getAllOutboundOrders()
    if (response.code === 200) {
      actualData.value = response.data.filter((item: any) => item.bkThumbnail)
      ElMessage.success(`加载了 ${actualData.value.length} 条有图片的数据`)
    } else {
      ElMessage.error('加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 处理图片加载成功
const handleImageLoad = (outboundId: number) => {
  imageStatuses[outboundId] = 'success'
  console.log(`图片加载成功 - 出库单ID: ${outboundId}`)
}

// 处理图片加载失败
const handleImageError = (outboundId: number) => {
  imageStatuses[outboundId] = 'error'
  console.log(`图片加载失败 - 出库单ID: ${outboundId}`)
}
</script>

<style scoped>
.image-path-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.url-list {
  margin-bottom: 30px;
}

.url-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.url-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.url-index {
  font-weight: bold;
  color: #409eff;
  min-width: 30px;
}

.url-text {
  flex: 1;
  font-family: monospace;
  word-break: break-all;
}

.url-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.url-status.loading {
  background: #e6f7ff;
  color: #1890ff;
}

.url-status.success {
  background: #f6ffed;
  color: #52c41a;
}

.url-status.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.test-image {
  max-width: 200px;
  max-height: 150px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.data-section {
  margin-bottom: 30px;
}

.actual-data {
  margin-top: 20px;
}

.data-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.item-info {
  margin-bottom: 10px;
  line-height: 1.6;
}

.image-test {
  display: flex;
  align-items: center;
  gap: 15px;
}

.actual-image {
  max-width: 150px;
  max-height: 100px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.image-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.image-status.loading {
  background: #e6f7ff;
  color: #1890ff;
}

.image-status.success {
  background: #f6ffed;
  color: #52c41a;
}

.image-status.error {
  background: #fff2f0;
  color: #ff4d4f;
}
</style>
